




var GameInit = function(images, runCallBack) {
    // images 是一个数组， 里面是图片的名字
    // 加载完成所有图片后，开始运行程序

    var g = {
        scene: null,
        images:{},
        actions: {},  // 按键 和 回调
        keydowns: [], //存储按键状态
        update: function() { 
            scene.update()
        },
        draw: function() { 
            scene.draw()
        },
    }
    var canvas = document.querySelector('#xs_scene')
    var ctx = canvas.getContext('2d')
    g.canvas = canvas
    g.ctx = ctx
    // drawImage
    g.drawImage = function(xsImage) {
        g.ctx.drawImage(xsImage.image, xsImage.x, xsImage.y)
    }

    // events
    window.addEventListener('keydown', function(event) {
        console.log('keydown', event.key)
        g.keydowns[event.key] = true      
    })
    window.addEventListener('keyup', function(event) {
        console.log('keyup', event.key)
        g.keydowns[event.key] = false
    })

    g.registerAction = function(key, callback) {
        g.actions[key] = callback
    }
    g.imgByName = function(name) {
        return g.images[name]
    }


    g.runWithScene = function(scene) {
        g.scene = scene
        runloop()
    }
    g.replaceScene = function (scene) {
        g.scene = scene
    }

    var runloop = function () {
        var actions = Object.keys(g.actions)
        for (let i = 0; i < actions.length; i++) {
            const key = actions[i]
            if (g.keydowns[key]) {
                // 如果按键被按下，调用注册的 anction   
                // console.log('anctions', key, g.keydowns)
                g.actions[key]()
            }

        }
        // update
        g.scene.update();
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        // draw
        g.scene.draw()
        
        setTimeout(() => {
            // log('runloop',fps)
            runloop()
        }, 1000/fps);
    }


    var loads = []
    var imgNames = Object.keys(images)
    // 预先加载所有素材
    for (let i = 0; i < imgNames.length; i++) {
        let img = new Image()
        img.src = images[imgNames[i]]
        img.onload = function () {
            loads.push(1)
            g.images[imgNames[i]] = img
            if (loads.length == imgNames.length) {
                g.__start()
            }
        }
    }
    // 开始运行程序
    g.__start = function () {
        runCallBack(g)
    }
    return g
}

var XsGame = {
    instance: function (images, runCallBack) {
        this.i = this.i || new this.init(images, runCallBack)
        return this.i
    },
    init: GameInit,
}